package com.benjaminwan.read.free.utils

import android.content.Context
import android.view.View
import com.benjaminwan.read.free.model.ItemOption
import com.benjaminwan.read.free.model.nameList
import com.xuexiang.xui.widget.picker.widget.OptionsPickerView
import com.xuexiang.xui.widget.picker.widget.builder.OptionsPickerBuilder
import com.xuexiang.xui.widget.picker.widget.listener.OnOptionsSelectListener
import com.xuexiang.xui.widget.textview.supertextview.SuperTextView

fun Context.showPicker(
    title: String,
    options: List<ItemOption>,
    preFill: String,
    listener: (opValue: Int, opName: String) -> Unit
) {
    val innerListener =
        OnOptionsSelectListener { view, options1, options2, options3 ->
            listener.invoke(options[options1].value, options[options1].name)
            false
        }
    val picker: OptionsPickerView<String> =
        OptionsPickerBuilder(this, innerListener)
            .isDialog(true)
            .setTitleText(title)
            .setSelectOptions(
                getOptionIndex(options, preFill)
            )
            .build()
    picker.setPicker(options.nameList)
    picker.show()
}

fun View.showPicker(
    title: String,
    options: List<ItemOption>,
    preFill: String,
    listener: (opValue: Int, opName: String) -> Unit
) = this.context.showPicker(title, options, preFill, listener)

fun SuperTextView.showPicker(
    title: String,
    options: List<ItemOption>,
    listener: (opValue: Int, opName: String) -> Unit
) {
    this.context.showPicker(title, options, this.rightString, listener)
}

fun getOptionIndex(options: List<ItemOption>, optionName: String, defIndex: Int = 0): Int {
    val foundIndex = options.withIndex().find { indexedValue: IndexedValue<ItemOption> ->
        indexedValue.value.name == optionName
    }
    return foundIndex?.index ?: defIndex
}

fun getOptionIndex(options: Array<ItemOption>, optionName: String, defIndex: Int = 0): Int =
    getOptionIndex(
        options.toList(),
        optionName,
        defIndex
    )

fun getOptionValue(options: List<ItemOption>, optionName: String, defValue: Int = 0): Int {
    val foundItem = options.find { it.name == optionName }
    return foundItem?.value ?: defValue
}

fun getOptionValue(options: Array<ItemOption>, optionName: String, defValue: Int = 0): Int {
    val foundItem = options.find { it.name == optionName }
    return foundItem?.value ?: defValue
}

fun getOptionName(
    optionList: List<ItemOption>,
    value: Int,
    defStr: String = "无"
): String {
    val foundItem = optionList.find { it.value == value }
    return foundItem?.name ?: defStr
}